Skip to content

productstats: collect the documented list - #8788

Open
theomonnom wants to merge 23 commits into
v2.0from
theo/productstats-list
Open

theomonnom wants to merge 23 commits into
v2.0from
theo/productstats-list

Conversation

@theomonnom

Copy link
Copy Markdown
Member

No description provided.

…command and storage on the resource

Every product statistics key starts with lk.product.agents.; lk-agents-codegen --check
refuses a productstats declaration without the prefix and any other declaration with it.
The resource names the host's runtime (python, node, bun) and its version instead of a
Python-only key, the runner's command as runner.cmd (the Runner field, the IPC hello
field and the env accessors say cmd), and the thread storage the process opened
(agent_db, sqlite or none). The runner declarations move under abi::productstats.
Each model metric carries model.kind, model.plugin, model.provider and model.name, derived
from the identity the model declares: the plugin from its class path (livekit-inference
for the Inference models, custom outside livekit.plugins), the provider and name as
declared, an Inference model string split into its vendor and model, and a provider that
reads as a host never sent.

model.requests, input_tokens, output_tokens, characters and audio_duration count what a
model was measured in; model.ttft and model.ttfb time its first output. An LLM and a TTS
are counted at their request, an STT at its stream or recognition and by what the session
heard it report, a realtime or duplex model at each response of the model installed.

model.transcription_delay is measured once per turn from the end of speech the VAD or
the STT detected, labelled by which did; a final that came first records nothing.

A sans-I/O machine makes a ProductStat where the fact is known and it leaves with the
session's telemetry records; the tracer hands it to the process's product statistics.
… start

sessions counts a call (rtc_session) or a text request (a2a_session) once when it ends,
with its topology (single, handoff, agent_as_tool, both) and delegation (none, remote).
The facts are the ones the machines already decide: an agent replacing another, a tool
body starting for a local agent or a RemoteAgent. A voice session reports them with its
closing telemetry records; a text request's runs report them to their turn, which counts
the request when it ends.

voice.sessions counts a voice session once when it opens, with its pipeline, the turn
detection it resolved, the interruption mode it runs and whether a false interruption
pauses and resumes its speech.
# Conflicts:
#	rust/crates/lk-agents-inference/src/telemetry.rs
feature.mcp, update_options, override_options, background_audio, language_switch and
model_switch each count a session the first time it uses the feature, model_switch once
per kind of model changed. A session holds what it already counted (SessionFeatures).

An agent definition says whether it has an MCP toolset; a voice session counts it when
the agent runs, a text request when it ends. update_options, override_options and a
background audio player started for a session are counted at the session owner. The
voice machine counts a language switch when the STT's reported language changes, and a
model switch when a model other than the one the session started with is installed.
@theomonnom
theomonnom requested a review from a team as a code owner November 25, 2026 20:44

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 5 potential issues.

3 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

}
Event::HostError(_) | Event::ServerGeneration(_) => {}
Event::Metrics(rt::RealtimeMetrics { metrics }) => {
self.count_realtime_response(&metrics);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Missing built-in duplex response statistics

count_realtime_response never runs for built-in duplex replies. The duplex segmenter emits GenerationDone, not Metrics, so those replies contribute neither request counts nor first-token timings.

Learn more

Voice sessions receive a stream of events from their model. The built-in duplex session forwards segmenter events, and the segmenter marks each response complete without emitting a metrics event. Product statistics currently run only from the metrics event arm.

Example: Start a voice session on the built-in openai/gpt-live-1 model and let it complete a reply. The voice session count includes the duplex pipeline, but the reply adds nothing to the model request count.

Recommended fix: Record duplex response statistics from the duplex response lifecycle, or have the duplex driver emit one real response measurement per response. Track the first output separately and emit timing only when observed. Ensure providers that already emit response metrics are not counted twice.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +169 to +177
pub(crate) fn count_realtime_response(&mut self, metrics: &AgentMetrics) {
let AgentMetrics::RealtimeModel(response) = metrics else { return };
let Some(realtime) = self.activity.realtime() else { return };
let kind = match realtime.capabilities.supports_overlapping_speech {
true => ModelKind::Duplex,
false => ModelKind::Realtime,
};
let model = ModelLabels::of(kind, &realtime.provider);
let mut stats = vec![ProductStat::of(&ModelRequests { model: model.clone() }, 1u64)];

@devin-ai-integration devin-ai-integration Bot Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Realtime connections counted as responses

count_realtime_response counts a request when a realtime socket opens or reconnects. Connection metrics use the same record type as response metrics, even when the model has not replied.

Learn more

The native OpenAI-compatible session publishes connection acquisition before applying its open or reconnect step. The connection record sets acquire_time but has no response ID. The response record uses the same enum variant. The product counter does not distinguish them.

Example: A caller joins a voice session and leaves without asking a question. Opening the model connection increments the request counter once even though the model generated no response.

Recommended fix: Separate response records from connection-only records at the product-statistics boundary. Add a test that feeds a real connection-acquisition record and a response record and expects exactly one request.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +479 to +480
if let (Some(_), Some(metrics)) = (&self.span, metrics) {
let model = ModelStats::of(ModelKind::Tts, &self.id);

@devin-ai-integration devin-ai-integration Bot Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Fallback synthesis credited to wrong model

When a TTS fallback serves a request on a different member, TtsTrace::end credits the member selected before synthesis. Member traces end without usage and cannot correct that attribution.

Learn more

The voice runtime opens the trace before starting synthesis. A fallback adapter’s identity describes its active member at the time it is read. The trace keeps that initial identity, but its final metrics describe the member that actually produced the audio. The separately traced attempts do not record usage.

Example: A request starts with Cartesia active. Cartesia fails before yielding audio, and the fallback serves the request through ElevenLabs. The request statistics count the ElevenLabs attempt, but its audio and time to first audio are credited to Cartesia.

Recommended fix: Carry the serving member’s ProviderId with the synthesis result and use it for product usage and latency. Avoid rereading the adapter’s shared active member at the end, since a different request can change it.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +393 to +398
pub fn transcription_after_endpoint(&self) -> Option<(Duration, EndpointedBy)> {
self.metrics.transcription_delay?;
let turn = &self.snapshot;
let (stopped, transcribed) = (turn.last_speaking_time?, turn.last_final_transcript_time?);
let by = turn.speech_ended_by.filter(|_| transcribed > stopped)?;
Some((transcribed.saturating_duration_since(stopped), by))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Preflight transcripts counted as finals

transcription_after_endpoint can record a delay when a turn commits using preflight text and no final transcript has arrived. Preflight handling writes to the same timestamp used for finals.

Learn more

The recognition machine uses one timestamp for final and preflight transcript arrivals. That timestamp is useful to its existing turn detection logic, but it does not establish that a final arrived. Turn commit can promote interim text and copy the shared timestamp into the turn snapshot used by product statistics.

Example: VAD marks the end of speech, the STT sends a preflight transcript, and the turn commits on that text before the final arrives. The current histogram treats the preflight delay as the final transcript delay.

Recommended fix: Track actual final-transcript arrival separately for product statistics. Preserve the shared timestamp for the existing turn detection logic. Test a turn that commits on preflight text, followed by its actual final.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

EXPORTER in lk_agents_net::export::productstats is the only product statistics static.
measure and record move there from lk-agents-telemetry, whose sink, Sink trait and
testkit are deleted. A machine's Record::ProductStat travels with its session's records
to the customer exporter's record(), which hands it to the product statistics exporter
and never queues it.

The runner command is passed in when the exporter is built: the CLI names it on the
server, the host passes it to the telemetry installation, and a worker hands it to its
job processes in their hello, which the child's initialize passes on. The storage kind
is a field of the exporter's resource, set by storage_opened. The opt-out is read at
installation instead of being cached.
…session-level ones included

An MCPToolset's lifecycle marks its toolset's lifetime port when it sets it up, and a
toolset group knows once started whether a toolset it started, or one nested in those,
is marked. A voice session's toolset scopes count feature.mcp once; a text request's
run resources report it to their turn, which counts it when the request ends. The
AgentDefinition.mcp field and the Python _mcp class marker are gone.
…tination of the one exporter

Recording is lk_agents_telemetry::productstats::measure(cx, &metric, value) in async
code and Trace::measure_product in a machine; both make a Record::ProductStat for the
context's recorder. No product statistics static remains.

The OTLP exporter gets a third destination beside Cloud and the application: it takes
only ProductStats, aggregates them with delta temporality under its own resource and
posts one window a minute to LiveKit Cloud's collector, belonging to no job and gated by
no recording decision. The separate exporter in export/productstats is deleted.

One SessionStats per session (what its agents did, the features it used) is filled by
the voice session and by the text request and emitted once when the session ends. The
runtime tells the voice machine the features it saw with a FeatureUsed command.
…policy is pinned, docs describe one exporter with three destinations

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 2 new potential issues.

5 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

/// adapter's members count their own.
fn request(&self, cx: &telemetry::Cx) {
if !self.stt.retries_itself() {
telemetry::model_request(cx, ModelKind::Stt, &self.stt.id());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Missing STT requests through node overrides

When a voice override calls the default STT node, Report::request receives a context without a recorder. Transcription works, but the collector never receives the model request count.

Learn more

The Python default STT node forwards the session's provider and call information to the native node. The native node opens the provider under Cx::NONE. Product statistic recording requires a recorder, so that request count disappears even when a Cloud-connected process has an exporter.

Example: Wrap session.default.stt_node(...) in a custom audio-filtering node and use a streaming STT provider. The user gets transcripts, but the provider's stream contributes nothing to the product request counter.

Recommended fix: Pass a recorder-bearing context from the native STT default node into the inference call. Reuse the session's node context or process tracer fallback, following request_cx, and test through the override path.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

…ared audience

measure(cx, &metric, value) and Trace::measure(&metric, value) take a metric of either
audience. The sealed Audience trait turns a measurement into its record
(Record::Measurement or Record::ProductStat), so nothing a caller passes chooses the
destination, and ProductStat can be built only by its audience inside ABI. productstats::
measure, Trace::measure_product and MeasureProduct are gone; the emitters shared by
machines and async code take the small Measure trait, implemented by &Cx and &mut Trace.
Events keep an observability bound like spans.
…mpile time

#[span], #[event] and #[metric] assert in their expansion that a declaration is for
product statistics exactly when its name starts with lk.product.agents. and exactly when
it is declared in abi::productstats; #[derive(Attrs)] asserts the same of each key. A
product statistic's fields must be Bounded, a sealed marker of closed enums, bounded
labels and groups of them, so content, free text or an id cannot be declared in one.
…ence checks; docs list what keeps the audiences apart
…thout a session

The Rust player counts feature.background_audio when it starts, under the process
tracer's root context. It leaves the per-session summary, and the session's
_core_background_audio hook is deleted.
…e server's run

The parser derives runner_cmd on the start arguments (simulation, dev or start); the
console passes RunnerCmd.Console. AgentServer._run takes it as a keyword argument and
hands it to the telemetry installation; the server keeps no _runner_cmd attribute.
feature.model_switch has two labels, feature.model_switch.from.kind and .to.kind, each a
ModelKind. From is the model installed in the slot just before; a model installed where
the session had none, the same identity installed again, or a fallback adapter installed
over a fallback adapter is no switch. A session counts each distinct pair once.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 new potential issue.

5 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +439 to +440
// A child frame's first invocation, with its task: a local agent called as a tool.
let agent_tool = message.is_some() && frame.parent.is_some();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Duplicate tool counts on follow-up replies

When a user answers a local agent’s follow-up question, invoke_offered marks the resumed child as a new tool call. The text session driver counts the same call again.

Learn more

The text session creates a child frame when a parent invokes a local agent as a tool. next_child creates that frame and invokes it with a generated task message. A child asking for input keeps its frame in the session snapshot, as shown by the reconstruction test. A reply comes through input_routed, which passes the reply as a message to the same frame. The text session driver emits one measurement every time this flag is true.

Example: The booking agent is called once and asks “Which date?” When the user replies “Friday,” the original booking call resumes, but the feature counter increases from one to two.

Recommended fix: Carry an explicit new-child origin from next_child into InvocationStarted; pass false for human input, history continuation, and remote recovery. Extend the reconstruction test to assert that the reply starts an invocation without setting agent_tool.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant